//package com.zmn.plat.admin.controller.channel;
//
//import com.alibaba.fastjson.JSON;
//import com.google.common.base.Strings;
//import com.google.common.collect.Lists;
//import com.zmn.common.constant.GlobalConsts;
//import com.zmn.common.dictionary.GlobalDict;
//import com.zmn.common.dto.KvDTO;
//import com.zmn.common.dto.VtDTO;
//import com.zmn.common.dto2.ResponseDTO;
//import com.zmn.common.utils.math.MathUtil;
//import com.zmn.common.utils.number.NumberUtil;
//import com.zmn.common.utils.reflect.BeanMapper;
//import com.zmn.common.utils.string.StringUtil;
//import com.zmn.manager.common.database.annotation.ReadOnlyConnection;
//import com.zmn.mcc.cas.web.StaffAdminService;
//import com.zmn.mcc.common.dto.dept.DeptDRO;
//import com.zmn.mcc.common.dto.staff.StaffDRO;
//import com.zmn.mcc.common.dto.staff.StaffSimpleQueryDIO;
//import com.zmn.mcc.dubbo.dto.DubboConsts;
//import com.zmn.mcc.dubbo.interfaces.dept.DeptListRemoteService;
//import com.zmn.plat.business.interfaces.channel.ChannelServProductBService;
//import com.zmn.plat.business.interfaces.channel.ChannelServiceCategoryBService;
//import com.zmn.plat.common.constant.ChannelConsts;
//import com.zmn.plat.common.constant.CompanyConsts;
//import com.zmn.plat.common.constant.ProductConsts;
//import com.zmn.plat.common.dictionary.*;
//import com.zmn.plat.common.exception.PlatException;
//import com.zmn.plat.common.util.ChannelLogUtil;
//import com.zmn.plat.common.util.CompareObjectUtil;
//import com.zmn.plat.common.util.DataUtils;
//import com.zmn.plat.common.util.image.QRCodeUtil;
//import com.zmn.plat.manager.dictionary.MasterDict;
//import com.zmn.plat.manager.dictionary.ProductDict;
//import com.zmn.plat.model.dto.request.TreeNodeDTO;
//import com.zmn.plat.model.dto.xmselect.XmSelectPropDTO;
//import com.zmn.plat.model.entity.category.BaseCategoryQuery;
//import com.zmn.plat.model.entity.channel.*;
//import com.zmn.plat.model.entity.channel.commission.settle.rule.ChannelCommissionSettleRule;
//import com.zmn.plat.model.entity.channel.generalproduct.ChannelGeneralProductSwitch;
//import com.zmn.plat.model.entity.channel.order.config.ChannelOrderConfig;
//import com.zmn.plat.model.entity.channel.product.map.ChannelProductMap;
//import com.zmn.plat.model.entity.channel.product.map.ChannelProductMapQuery;
//import com.zmn.plat.model.entity.company.BaseCompany;
//import com.zmn.plat.model.entity.company.BaseCompanyQuery;
//import com.zmn.plat.model.entity.product.ChannelProductQuery;
//import com.zmn.plat.model.vo.channel.ChannelServProductVO;
//import com.zmn.plat.model.vo.company.BaseCompanyVO;
//import org.apache.commons.io.IOUtils;
//import org.apache.dubbo.config.annotation.Reference;
//import org.apache.shiro.authz.annotation.Logical;
//import org.apache.shiro.authz.annotation.RequiresPermissions;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.BeanUtils;
//import org.springframework.core.io.ClassPathResource;
//import org.springframework.stereotype.Controller;
//import org.springframework.util.CollectionUtils;
//import org.springframework.util.StringUtils;
//import org.springframework.web.bind.annotation.*;
//import org.springframework.web.servlet.ModelAndView;
//
//import javax.annotation.Resource;
//import javax.imageio.ImageIO;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.awt.image.BufferedImage;
//import java.io.*;
//import java.math.BigDecimal;
//import java.net.URLEncoder;
//import java.text.SimpleDateFormat;
//import java.util.*;
//import java.util.concurrent.ExecutionException;
//import java.util.function.BiFunction;
//import java.util.function.Function;
//import java.util.regex.Matcher;
//import java.util.regex.Pattern;
//import java.util.stream.Collectors;
//import java.util.stream.IntStream;
//
//
///**
// * 渠道ListController
// *
// * @author xiangjunming
// * @since 2019 /08/19 19:10:20
// */
//@Controller
//@RequestMapping("/channel/")
//public class ChannelListController extends ChannelBaseController {
//
//    private Logger logger = LoggerFactory.getLogger(ChannelListController.class);
//
//    // 渠道管理员
//    private static List<Integer> channelManagerIds = Arrays.asList(16192, 18192, 161462);
//
//    @Reference(version = DubboConsts.INTERFACE_VERSION, check = false)
//    private DeptListRemoteService deptListRemoteService;
//
//    @Resource
//    private ChannelServProductBService channelServProductBService;
//
//    @Resource
//    private ChannelServiceCategoryBService channelServiceCategoryBService;
//
//
//    /**
//     * 渠道列表
//     *
//     * @param query the query
//     * @return the model and view
//     * @author xiangjunming
//     * @since 2019/9/5
//     */
//    @RequestMapping(value = "list")
//    @RequiresPermissions("/channel/list.action")
//    @ReadOnlyConnection
//    public ModelAndView list(ChannelQuery query) {
//
//        ModelAndView mav = new ModelAndView("channel/list");
//
//        if (query.getReceivables() != null && query.getReceivables().size() > 0) {
//            String receivablesStr = query.getReceivables().stream().sorted().map(Objects::toString).collect(Collectors.joining(","));
//            query.setReceivablesStr(receivablesStr);
//        }
//
//        List<Channel> channels = channelService.listPageByQuery(query, getMcStaffId());
//
//        mav.addObject("query", query);
//        mav.addObject("items", channels);
//        mav.addObject("plats", GlobalConsts.getPlatList());
//        mav.addObject("oneChannels", getOneChannels());
//        mav.addObject("oneDepts", getOneDeptList());
//        mav.addObject("twoDepts", getTwoDeptList());
//        mav.addObject("provinces", getProvinceList());
//        mav.addObject("citys", getCityList());
//        mav.addObject("channelTypes", ChannelTypeEnum.enables());
//        mav.addObject("channelLevels", ChannelLevelEnum.values());
//        mav.addObject("statusList", StatusEnum.values());
//        mav.addObject("receivablesLimits", ChannelReceivablesLimitEnum.values());
//        mav.addObject("faultTariffs", faultTariffService.listAll());
//        mav.addObject("channelAccessModes", ChannelDict.getChannelAccessModeListItems());
//
//        return mav;
//    }
//
//    /**
//     * 选择渠道页面
//     *
//     * @param query
//     * @return the model and view
//     * @author xiangjunming
//     * @since 2019/10/29
//     */
//    @RequestMapping(value = "select/list")
//    @ReadOnlyConnection
//    public ModelAndView select(ChannelSelectCommitVO commitVO, ChannelQuery query) {
//        ModelAndView mav = new ModelAndView("channel/select/list");
//        List<Channel> channels = channelService.listPageByQuery(query, getMcStaffId());
//        List<Integer> parentIds = channels.stream().map(Channel::getParentId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
//        List<ChannelSelectVO> items = BeanMapper.mapList(channels, ChannelSelectVO.class);
//        if (parentIds.size() > 0) {
//            Map<Integer, String> parentMap = channelService.listByChannelIds(parentIds).stream().collect(Collectors.toMap(Channel::getChannelId, Channel::getName));
//            items.forEach(item -> item.setParentName(parentMap.get(item.getParentId())));
//        }
//        mav.addObject("items", items);
//        mav.addObject("plats", GlobalConsts.getPlatList());
//        mav.addObject("channelTypes", ChannelTypeEnum.enables());
//        mav.addObject("query", query);
//        mav.addObject("commitVO", commitVO);
//        return mav;
//    }
//
//    /**
//     * 渠道保外价格/保内价格/工程价格
//     *
//     * @param channelId
//     * @return
//     */
//    @RequestMapping(value = "priceList")
//    public ModelAndView priceList(@RequestParam("channelId") Integer channelId, String addFlag, Integer bizType, Integer priceType) {
//        ModelAndView mav = new ModelAndView("channel/priceList");
//        Channel obj = channelService.findByKey(channelId);
//        if (NumberUtil.isNullOrZero(priceType)) {
//            priceType = PriceTypeEnum.PRICE.getCode();
//        }
//        ChannelCityPriceRatioQuery channelCityPriceRatioQuery = new ChannelCityPriceRatioQuery();
//        channelCityPriceRatioQuery.setRatioType(ChannelCityRatioTypeEnum.DISCOUNTRATIO.getCode());
//        channelCityPriceRatioQuery.setPriceType(priceType);
//        channelCityPriceRatioQuery.setChannelId(channelId);
//        channelCityPriceRatioQuery.setBizType(bizType);
//        ChannelCityPriceRatio channelCityPriceRatio =
//                cityPriceRatioService.findByChannelIdAndCityAndCategAndType(channelCityPriceRatioQuery);
//        if (channelCityPriceRatio == null) {
//            channelCityPriceRatio = new ChannelCityPriceRatio();
//            channelCityPriceRatio.setChannelId(channelId);
//        }
//
//        List<ChannelFaultPriceVO> faultPrices = channelTariffService.listByChannelId(channelId);
//
//        Optional<ChannelFaultPriceVO> servicePrice = faultPrices.stream().filter(item -> Objects.equals(bizType, item.getBizType()))
//                .filter(item -> Objects.equals(ProductDict.TRIFF_TYPE_SERVICE, item.getTariffType())).findFirst();
//
//        Optional<ChannelFaultPriceVO> faultPrice = faultPrices.stream().filter(item -> Objects.equals(bizType, item.getBizType()))
//                .filter(item -> Objects.equals(ProductDict.TRIFF_TYPE_TARIFF, item.getTariffType())).findFirst();
//
//        Optional<ChannelFaultPriceVO> prepay = faultPrices.stream().filter(item -> Objects.equals(bizType, item.getBizType()))
//                .filter(item -> Objects.equals(ProductDict.TRIFF_TYPE_ADVANCE, item.getTariffType())).findFirst();
//
//        Optional<ChannelFaultPriceVO> tariff3 = faultPrices.stream().filter(item -> Objects.equals(bizType, item.getBizType()))
//                .filter(item -> Objects.equals(ProductDict.TRIFF_TYPE_TARIFF3, item.getTariffType())).findFirst();
//
//
//        List<ChannelFaultPriceVO> items = new ArrayList<>();
//        items.add(servicePrice.orElseGet(() -> new ChannelFaultPriceVO() {
//            {
//                setChannelId(channelId);
//                setBizType(bizType);
//                setTariffType(ProductDict.TRIFF_TYPE_SERVICE);
//            }
//        }));
//        items.add(faultPrice.orElseGet(() -> new ChannelFaultPriceVO() {
//            {
//                setChannelId(channelId);
//                setBizType(bizType);
//                setTariffType(ProductDict.TRIFF_TYPE_TARIFF);
//            }
//        }));
//        items.add(prepay.orElseGet(() -> new ChannelFaultPriceVO() {
//            {
//                setChannelId(channelId);
//                setBizType(bizType);
//                setTariffType(ProductDict.TRIFF_TYPE_ADVANCE);
//            }
//        }));
//        items.add(tariff3.orElseGet(() -> new ChannelFaultPriceVO() {
//            {
//                setChannelId(channelId);
//                setBizType(bizType);
//                setTariffType(ProductDict.TRIFF_TYPE_TARIFF3);
//            }
//        }));
//        Integer mergeSettle = getMergeSettle(channelId);
//        obj.setMergeSettle(mergeSettle);
//        mav.addObject("obj", obj);
//        mav.addObject("flag", 5);
//        mav.addObject("addFlag", addFlag);
//        mav.addObject("channelId", channelId);
//        mav.addObject("bizType", bizType);
//        mav.addObject("priceType", priceType);
//        mav.addObject("channelRatio", channelCityPriceRatio);
//        mav.addObject("items", items);
//        return mav;
//    }
//
//    @RequestMapping("toCopyChannelRatio")
//    public ModelAndView toCopyChannelRatio(Integer channelId, Integer bizType, Integer priceType) {
//        List<Channel> channelList =
//                channelService.listAll().stream().filter(item -> !Objects.equals(item.getChannelId(), channelId)).collect(Collectors.toList());
//        ModelAndView mav = new ModelAndView("channel/copyChannelRatio");
//        mav.addObject("channelId", channelId);
//        mav.addObject("channelList", channelList);
//        mav.addObject("bizType", bizType);
//        mav.addObject("priceType", priceType);
//        return mav;
//    }
//
//    /**
//     * 设置渠道默认保内/保外系数
//     *
//     * @param channelId
//     * @param priceType
//     * @param bizType   1保外 2保内 3工程
//     * @return
//     */
//    @RequestMapping("channelRatio")
//    public ModelAndView channelRatio(Integer channelId, Integer bizType, Integer priceType) {
//        ChannelCityPriceRatioQuery channelCityPriceRatioQuery = new ChannelCityPriceRatioQuery();
//        channelCityPriceRatioQuery.setBizType(bizType);
//        channelCityPriceRatioQuery.setChannelId(channelId);
//        channelCityPriceRatioQuery.setPriceType(priceType);
//        channelCityPriceRatioQuery.setRatioType(ChannelCityRatioTypeEnum.CHANNELRATIO.getCode());
//        ChannelCityPriceRatio channelCityPriceRatio =
//                cityPriceRatioService.findByChannelIdAndCityAndCategAndType(channelCityPriceRatioQuery);
//        if (channelCityPriceRatio == null) {
//            channelCityPriceRatio = new ChannelCityPriceRatio();
//            channelCityPriceRatio.setChannelId(channelId);
//        }
//        ModelAndView mav = new ModelAndView("channel/setchannelratio");
//        if (bizType == ProductConsts.BIZ_TYPE_C) {
//            // C类业务价格系数返回计价器3.0默认系数
//            channelCityPriceRatioQuery.setRatioType(ChannelCityRatioTypeEnum.CHANNELCITYMETER3RATIO.getCode());
//            ChannelCityPriceRatio channelCityPriceRatioM =
//                    Optional.ofNullable(cityPriceRatioService.findByChannelIdAndCityAndCategAndType(channelCityPriceRatioQuery))
//                            .orElse(new ChannelCityPriceRatio());
//            mav.addObject("meterRatio", channelCityPriceRatioM.getToBeEffectiveRatio() == null ? channelCityPriceRatioM.getRatio() : channelCityPriceRatioM.getToBeEffectiveRatio());
//        }
//        mav.addObject("channelRatio", channelCityPriceRatio);
//        mav.addObject("bizType", bizType);
//        mav.addObject("priceType", priceType);
//        // 1表示设置系数
//        mav.addObject("type", 1);
//        return mav;
//    }
//
//    @RequestMapping("channelDiscount")
//    public ModelAndView channelDiscount(Integer channelId, Integer bizType, Integer priceType) {
//        ChannelCityPriceRatioQuery channelCityPriceRatioQuery = new ChannelCityPriceRatioQuery();
//        channelCityPriceRatioQuery.setBizType(bizType);
//        channelCityPriceRatioQuery.setChannelId(channelId);
//        channelCityPriceRatioQuery.setPriceType(priceType);
//        channelCityPriceRatioQuery.setRatioType(ChannelCityRatioTypeEnum.DISCOUNTRATIO.getCode());
//        ChannelCityPriceRatio channelCityPriceRatio =
//                cityPriceRatioService.findByChannelIdAndCityAndCategAndType(channelCityPriceRatioQuery);
//        if (channelCityPriceRatio == null) {
//            channelCityPriceRatio = new ChannelCityPriceRatio();
//            channelCityPriceRatio.setChannelId(channelId);
//        }
//        ModelAndView mav = new ModelAndView("channel/setchanneldiscount");
//        mav.addObject("channelRatio", channelCityPriceRatio);
//        mav.addObject("bizType", bizType);
//        mav.addObject("priceType", priceType);
//        return mav;
//    }
//
//    @RequestMapping(value = "detail")
//    @RequiresPermissions("/channel/addEditView.action")
//    @ReadOnlyConnection
//    public ModelAndView detail(Integer channelId, String addFlag, ChannelLogQuery logQuery) throws ExecutionException, InterruptedException {
//        ModelAndView mav = null;
//        Channel obj = channelService.findByKey(channelId);
//        if (obj.getRank() == com.zmn.plat.manager.dictionary.ChannelDict.RANK_ONE) {
//            mav = detailOne(channelId, addFlag, logQuery);
//        } else {
//            mav = detailTwo(channelId, addFlag, logQuery);
//        }
//        boolean detailNameUpdate = StaffAdminService.isPermitted("/channel/detail/name");
//        mav.addObject("detailNameUpdate", detailNameUpdate);
//        return mav;
//    }
//
//    /**
//     * 一级渠道详情
//     *
//     * @param channelId the channel id
//     * @return the model and view
//     * @author xiangjunming
//     * @since 2019/9/5
//     */
//    @RequestMapping(value = "detailOne")
//    @RequiresPermissions("/channel/addEditView.action")
//    @ReadOnlyConnection
//    public ModelAndView detailOne(Integer channelId, String addFlag, ChannelLogQuery query) throws ExecutionException, InterruptedException {
//
//        ModelAndView mav = new ModelAndView("channel/detailOne");
//        Channel obj = channelId != null && channelId > 0 ? channelService.findByKey(channelId) : new Channel();
//        Integer mergeSettle = getMergeSettle(channelId);
//        obj.setMergeSettle(mergeSettle);
//        BaseCompanyQuery baseCompanyQuery = new BaseCompanyQuery();
//        baseCompanyQuery.setType(CompanyConsts.COMPANY_TYPE_SUBSIDIARY);
//        List<BaseCompany> subCompanyList = baseCompanyService.listByQuery(baseCompanyQuery);
//        List<BaseCompany> currentPlatSubCompanyList = subCompanyList.stream().filter(e -> Objects.equals(obj.getPlat(), e.getPlat())).collect(Collectors.toList());
//        mav.addObject("allSubCompanyList", subCompanyList);
//        mav.addObject("currentPlatSubCompanyList", currentPlatSubCompanyList);
//
//        mav.addObject("obj", obj);
//        mav.addObject("plats", GlobalConsts.getPlatList());
//        mav.addObject("provinces", getProvinceList());
//        mav.addObject("citys", getCityList());
//        mav.addObject("oneDepts", getOneDeptList());
//        mav.addObject("twoDepts", getTwoDeptList());
//        mav.addObject("flag", 1);
//        mav.addObject("addFlag", addFlag);
//        boolean channelTypeEnable = Objects.equals(obj.getChannelType(), ChannelTypeEnum.CJ.getCode())
//                || Objects.equals(obj.getChannelType(), ChannelTypeEnum.SP.getCode());
//        mav.addObject("channelTypes", channelTypeEnable ? ChannelTypeEnum.enables() : ChannelTypeEnum.list());
//        mav.addObject("channelTypeEnable", channelTypeEnable);
//        mav.addObject("channelLevels", ChannelLevelEnum.values());
//        mav.addObject("channelAccessModes", ChannelDict.getChannelAccessModeListItems());
//        mav.addObject("customerTypes", ChannelCustomerTypeEnum.values());
//        mav.addObject("query", query);
//        mav.addObject("logs", listPageChannelLogByChannelId(query));
//        mav.addObject("rank", 1);
//        return mav;
//    }
//
//    /**
//     * 二级渠道详情
//     *
//     * @param channelId the channel id
//     * @return the model and view
//     * @author xiangjunming
//     * @since 2019/9/5
//     */
//    @RequestMapping(value = "detailTwo")
//    @RequiresPermissions("/channel/addEditView.action")
//    @ReadOnlyConnection
//    public ModelAndView detailTwo(Integer channelId, String addFlag, ChannelLogQuery logQuery) throws ExecutionException, InterruptedException {
//
//        ModelAndView mav = new ModelAndView("channel/detail");
//        Channel obj = channelId != null && channelId > 0 ? channelService.findByKey(channelId) : new Channel();
//        Integer mergeSettle = getMergeSettle(channelId);
//        obj.setMergeSettle(mergeSettle);
//        BaseCompanyQuery baseCompanyQuery = new BaseCompanyQuery();
//        baseCompanyQuery.setType(CompanyConsts.COMPANY_TYPE_SUBSIDIARY);
//        List<BaseCompany> subCompanyList = baseCompanyService.listByQuery(baseCompanyQuery);
//        List<BaseCompany> currentPlatSubCompanyList = subCompanyList.stream().filter(e -> Objects.equals(obj.getPlat(), e.getPlat())).collect(Collectors.toList());
//        mav.addObject("allSubCompanyList", subCompanyList);
//        mav.addObject("currentPlatSubCompanyList", currentPlatSubCompanyList);
//        if(org.apache.commons.lang3.StringUtils.isNotEmpty(obj.getMobile())){
//            obj.setMobile(DataUtils.maskMobile(obj.getMobile()));
//        }
//        mav.addObject("obj", obj);
//        mav.addObject("plats", GlobalConsts.getPlatList());
//        mav.addObject("oneChannels", getOneChannels());
//        mav.addObject("oneDepts", getOneDeptList());
//        mav.addObject("twoDepts", getTwoDeptList());
//        mav.addObject("provinces", getProvinceList());
//        mav.addObject("citys", getCityList());
//        boolean channelTypeEnable = Objects.equals(obj.getChannelType(), ChannelTypeEnum.CJ.getCode())
//                || Objects.equals(obj.getChannelType(), ChannelTypeEnum.SP.getCode());
//        mav.addObject("channelTypes", channelTypeEnable ? ChannelTypeEnum.enables() : ChannelTypeEnum.list());
//        mav.addObject("channelPromotionTypes", ChannelPromotionTypeEnum.list());
//        mav.addObject("channelPromotionBrands", ChannelPromotionBrandEnum.list());
//        mav.addObject("channelTypeEnable", channelTypeEnable);
//        mav.addObject("channelLevels", ChannelLevelEnum.values());
//        mav.addObject("accessIdentitys", ChannelAccessIdentityEnum.values());
//        mav.addObject("channelAccessModes", ChannelDict.getChannelAccessModeListItems());
//        mav.addObject("statusList", StatusEnum.values());
//        mav.addObject("customerTypes", ChannelCustomerTypeEnum.values());
//        mav.addObject("flag", 1);
//        mav.addObject("addFlag", addFlag);
//        mav.addObject("rank", 2);
//
//        boolean hideContact = false;
//        if (!channelManagerIds.contains(getMcStaff().getStaffId())) {
//            // 当前登陆人为运营责任人隐藏联系人
//            ChannelQuery query = new ChannelQuery();
//            query.setAbutmenter(getMcStaff().getStaffId());
//            hideContact = !channelService.listByQuery(query).isEmpty();
//        }
//
//        mav.addObject("hideContact", hideContact);
//        mav.addObject("query", logQuery);
//        mav.addObject("logs", listPageChannelLogByChannelId(logQuery));
//        return mav;
//    }
//
//    @ResponseBody
//    @RequestMapping(value = "search/company")
//    public ResponseDTO<List<XmSelectPropDTO>> searchCompany(String keyword) {
//        BaseCompanyQuery query = new BaseCompanyQuery();
//        query.setKeyword(keyword);
//        List<BaseCompanyVO> data = baseCompanyService.listPageByQuery(query, null);
//        List<XmSelectPropDTO> list = data.stream().map(item -> XmSelectPropDTO.builder().name(item.getName())
//                .value(item.getCompanyId().toString()).disabled(item.getStatus() == GlobalConsts.NO).build()).collect(Collectors.toList());
//        return ResponseDTO.success(list);
//    }
//
//    @ResponseBody
//    @RequestMapping(value = "search/staff")
//    public ResponseDTO<List<XmSelectPropDTO>> searchStaff(Integer deptId, String keyword) {
//        List<StaffDRO> data;
//        if (!NumberUtil.isPositiveInteger(deptId)) {
//            data = staffListRemoteService.listStaffByKeyword(keyword, GlobalConsts.YES).getData();
//        } else {
//            StaffSimpleQueryDIO simpleQueryDIO = new StaffSimpleQueryDIO();
//            simpleQueryDIO.setKeyword(keyword);
//            simpleQueryDIO.setDeptIds(Collections.singletonList(deptId));
//            simpleQueryDIO.setStatus(GlobalConsts.YES);
//            data = staffListRemoteService.listSubAllDeptStaffByDeptId(simpleQueryDIO).getData();
//        }
//
//        List<XmSelectPropDTO> list =
//                data.stream()
//                        .map(item -> XmSelectPropDTO.builder().name(item.getDeptName() + "-" + item.getRealName())
//                                .value(item.getStaffId().toString()).deptName(item.getDeptName()).staffName(item
//                                        .getRealName()).disabled(item.getStatus() == GlobalConsts.NO).build())
//                        .collect(Collectors.toList());
//        return ResponseDTO.success(list);
//    }
//
//    @ResponseBody
//    @RequestMapping(value = "search")
//    public ResponseDTO<List<XmSelectPropDTO>> searchParent(String keyword, Integer plat, Integer rank) {
//
//        ChannelQuery query = new ChannelQuery();
//        query.setKeyword(keyword);
//        query.setPlat(plat);
//        query.setRank(rank);
//        List<Channel> data = channelService.listByQuery(query);
//        List<XmSelectPropDTO> list = data.stream().map(item -> XmSelectPropDTO.builder().name(item.getName())
//                .value(item.getChannelId().toString()).disabled(item.getStatus() == GlobalConsts.NO).build()).collect(Collectors.toList());
//        return ResponseDTO.success(list);
//    }
//
//    @ResponseBody
//    @RequestMapping(value = "/{channelId}")
//    public Channel channel(@PathVariable("channelId") Integer channelId) {
//        Channel byKey = channelService.findByKey(channelId);
//        return byKey;
//    }
//
//    @ResponseBody
//    @RequestMapping(value = "/getCompanyById")
//    public BaseCompany getCompanyById(Integer companyId) {
//        BaseCompany baseCompany = baseCompanyService.findByKey(companyId);
//        return baseCompany;
//    }
//
//    @ResponseBody
//    @RequestMapping(value = "/getStaffById")
//    public StaffDRO getStaffById(Integer staffId) {
//        ResponseDTO<StaffDRO> responseDTO = staffListRemoteService.getStaff(staffId);
//        if (!responseDTO.isSuccess()) {
//            return new StaffDRO();
//        }
//        return responseDTO.getData();
//    }
//
//    /**
//     * 渠道订单配置
//     *
//     * @param channelId the channel id
//     * @return the model and view
//     * @author xiangjunming
//     * @since 2019/9/5
//     */
//    @RequestMapping(value = "orderConfig")
//    @RequiresPermissions("/channel/orderConfig/addEditView.action")
//    @ReadOnlyConnection
//    public ModelAndView orderConfig(Integer channelId, String addFlag) {
//        ModelAndView mav = new ModelAndView("channel/orderConfig");
//        Channel obj = channelService.findByKey(channelId);
//        ChannelOrderConfig orderConfig = Optional.ofNullable(channelOrderConfigService.findByKey(channelId)).orElse(new ChannelOrderConfig());
//        Integer mergeSettle = getMergeSettle(channelId);
//        obj.setMergeSettle(mergeSettle);
//        mav.addObject("obj", obj);
//        mav.addObject("orderConfig", orderConfig);
//        mav.addObject("completeOrCancelTypes", ChannelWorkOrderTypeEnum.completeOrCancelType());
////        mav.addObject("specialOfferTypes", ChannelWorkOrderTypeEnum.specialOfferType());
//        mav.addObject("receivablesLimits", ChannelReceivablesLimitEnum.values());
//        mav.addObject("flag", 2);
//        mav.addObject("addFlag", addFlag);
//
//        List<VtDTO> channelList = Optional.ofNullable(channelService.listTwoLevelChannel(null, null))
//                .orElse(Collections.emptyList())
//                .stream()
//                .map(m -> new VtDTO(m.getChannelId(), m.getName()))
//                .collect(Collectors.toList());
//        mav.addObject("channelList", channelList);
//        List<DeptDRO> parentNodes = new ArrayList<>();
//        // 根节点id
//        List<Integer> expandedKeys = new ArrayList<>();
//        if (Objects.nonNull(orderConfig.getPriceAuditDeptId())) {
//            Integer parent = getParentId(orderConfig.getPriceAuditDeptId(), parentNodes);
//            expandedKeys.addAll(parentNodes.stream().map(e -> e.getDeptId()).collect(Collectors.toList()));
//            expandedKeys.add(parent);
//        }
//        mav.addObject("expandedKeys", expandedKeys);
//        return mav;
//    }
//
//    /**
//     * 服务分类
//     *
//     * @param channelId the channel id
//     * @param showType  产品分类 1后台 2前台
//     * @return the model and view
//     * @author xiangjunming
//     * @since 2019/9/5
//     */
//    @RequestMapping(value = "serviceCategory")
//    @RequiresPermissions("/channel/serviceCategory/addEditView.action")
//    @ReadOnlyConnection
//    public ModelAndView serviceCategory(Integer channelId, Integer showType, String addFlag) {
//        ModelAndView mav = new ModelAndView("channel/serviceCategory");
//        Channel obj = channelService.findByKey(channelId);
//        List<KvDTO<Integer, String>> servCategorys = super.getAllChildCategory((categoryQuery) -> categoryQuery.setShowType(showType));
//        List<ChannelServiceCategory> serviceCategoryList = categoryService.listByChannelId(channelId, showType);
//        List<String> categIds = serviceCategoryList.stream().map(p -> p.getServCategId() + "-" + p.getCategOneId() + "-" + p.getCategId())
//                .collect(Collectors.toList());
//        if (servCategorys != null && servCategorys.size() > 0) {
//            mav.addObject("currentServCategId", servCategorys.get(0).getKey());
//        }
//
//        List<ChannelGeneralProductSwitch> channelGeneralProductSwitches = channelGeneralProductSwitchService.listByChannelId(channelId);
//        Map<Integer, Boolean> switchMap = new HashMap<>();
//        if (channelGeneralProductSwitches != null) {
//            for (int i = 0; i < channelGeneralProductSwitches.size(); i++) {
//                if (channelGeneralProductSwitches.get(i).getStatus().equals(GlobalConsts.YES)) {
//                    switchMap.put(channelGeneralProductSwitches.get(i).getServCategId(), true);
//                } else {
//                    switchMap.put(channelGeneralProductSwitches.get(i).getServCategId(), false);
//                }
//            }
//        }
//        Integer mergeSettle = getMergeSettle(channelId);
//        obj.setMergeSettle(mergeSettle);
//        mav.addObject("categIds", categIds);
//        mav.addObject("servCategorys", servCategorys);
//        mav.addObject("switchMap", switchMap);
//        mav.addObject("obj", obj);
//        mav.addObject("flag", 3);
//        mav.addObject("showType", showType);
//        mav.addObject("addFlag", addFlag);
//        return mav;
//    }
//
//    /**
//     * 订单库存
//     *
//     * @param channelId the channel id
//     * @return the model and view
//     * @author xiangjunming
//     * @since 2019/9/5
//     */
//    @RequestMapping(value = "orderStock")
//    // @RequiresPermissions("/channel/orderStock/addEditView.action")
//    @ReadOnlyConnection
//    public ModelAndView orderStock(Integer channelId, String addFlag) {
//        ModelAndView mav = new ModelAndView("channel/orderStock");
//        Channel obj = channelService.findByKey(channelId);
//        mav.addObject("obj", obj);
//        mav.addObject("flag", 12);
//        mav.addObject("addFlag", addFlag);
//        mav.addObject("stockLimit", Arrays.asList(ChannelConsts.ORDER_STOCK_SPECIAL_CHANNEL).contains(channelId));
//        return mav;
//    }
//
//    /**
//     * 佣金设置
//     *
//     * @param channelId the channel id
//     * @return the model and view
//     * @author xiangjunming
//     * @since 2019/9/5
//     */
//    @RequestMapping(value = "commission")
//    @RequiresPermissions("/channel/commission/addEditView.action")
//    @ReadOnlyConnection
//    public ModelAndView commission(Integer channelId, String addFlag) {
//        ModelAndView mav = new ModelAndView("channel/commission");
//
//        Channel obj = channelService.findByKey(channelId);
//        ChannelCommissionSettleRule channelCommissionSettleRule = Optional.ofNullable(channelCommissionSettleRuleService.findByChannelId(channelId))
//                .orElse(new ChannelCommissionSettleRule());
//        channelCommissionSettleRule.setChannelId(channelId);
//
//        List<ChannelCommission> commissions = commissionService.listByChannelId(channelId);
//        commissions.forEach(item -> {
//            if (item.getEffectiveTime() == null) {
//                item.setCommissionTypeNew(item.getCommissionType());
//                item.setBaseTypeNew(item.getBaseType());
//                item.setCommissionNew(item.getCommissionCurrent());
//            }
//        });
//        Integer mergeSettle = getMergeSettle(channelId);
//        obj.setMergeSettle(mergeSettle);
//        mav.addObject("commissions", commissions);
//        mav.addObject("commissionSettleRule", channelCommissionSettleRule);
//        mav.addObject("obj", obj);
//        mav.addObject("flag", 6);
//        mav.addObject("addFlag", addFlag);
//        return mav;
//    }
//
//    /**
//     * 描述: 渠道服务产品
//     *
//     * @return org.springframework.web.servlet.ModelAndView
//     * @author linfeng
//     * @since 2019/11/12
//     **/
//    @RequestMapping(value = "servProductList")
//    @RequiresPermissions(value = {"/channel/servProductList.action", "/channel/tariff/servProductList.action"}, logical = Logical.OR)
//    @ReadOnlyConnection
//    @SuppressWarnings("Duplicates")
//    public ModelAndView servProductList(@ModelAttribute ChannelProductQuery query, String addFlag) {
//        if (StringUtil.isBlank(query.getName())) {
//            query.setName(null);
//        }
//        ModelAndView mav = new ModelAndView("channel/servproduct/list");
//        mav.addObject("flag", 10);
//        mav.addObject("addFlag", addFlag);
//        Channel obj = channelService.findByKey(query.getChannelId());
//
//        List<VtDTO> productErpEsTypeList = ProductDict.getProductErpEsTypeList();
//        if (Objects.isNull(query.getShowType())) {
//            query.setShowType(ProductDict.ERP_PRODUCT_TYPE);
//            productErpEsTypeList.forEach(pe -> {
//                pe.setStatus(Objects.equals(pe.getValue(), ProductDict.ERP_PRODUCT_TYPE));
//            });
//        } else {
//            productErpEsTypeList.forEach(pe -> {
//                pe.setStatus(Objects.equals(pe.getValue(), query.getShowType()));
//            });
//        }
//        Integer mergeSettle = getMergeSettle(query.getChannelId());
//        obj.setMergeSettle(mergeSettle);
//        mav.addObject("obj", obj);
//        mav.addObject("platTypeList", GlobalDict.getPlatTypeList());
//
//        List<VtDTO> servList = Optional.ofNullable(super.getServCategoryList())
//                .orElse(Collections.emptyList())
//                .stream()
//                .map(mm -> new VtDTO(mm.getCategId(), mm.getName(), mm.getStatus()))
//                .collect(Collectors.toList());
//        mav.addObject("servList", servList);
//        List<VtDTO> showServList = Optional.ofNullable(super.getServCategoryList())
//                .orElse(Collections.emptyList())
//                .stream()
//                .map(mm -> new VtDTO(mm.getCategId(), mm.getShowName(), mm.getStatus()))
//                .collect(Collectors.toList());
//        mav.addObject("showServList", showServList);
//
//        mav.addObject("productType", productErpEsTypeList);
//
//        try {
//            // 当前渠道不可以 取上级渠道
//            if (NumberUtil.isPositiveInteger(query.getChannelId())) {
//                Integer availableCategoryChannelId = channelServiceCategoryBService.getAvailableCategoryChannelId(query.getChannelId());
//                query.setChannelId(availableCategoryChannelId);
//            }
//        } catch (PlatException e) {
//            logger.error("渠道没配置可用的分类", e);
//        }
//
//        List<ChannelServProductVO> tableList = channelServProductBService.listChannelServProductByQuery(query);
//        query.setTotalCount(tableList.size());
//        tableList = tableList.stream().skip((long) (query.getPageIndex() - 1) * query.getPageSize())
//                .limit(query.getPageSize())
//                .collect(Collectors.toList());
//
//        tableList.forEach(e -> {
//            e.setBizTypeShowName(servProductService.translateBizTypeStrByBizType(e.getBizType()));
//        });
//
//        ChannelProductMapQuery channelProductMapQuery = new ChannelProductMapQuery();
//        channelProductMapQuery.setChannelId(query.getChannelId());
//        List<ChannelProductMap> channelProductMaps = channelProductMapService.listByQuery(channelProductMapQuery);
//
//        // 子级没有则其父级
//        try {
//            Integer parentChannelId = null;
//            if (CollectionUtils.isEmpty(channelProductMaps) && Objects.equals(obj.getRank(), 2) && Objects.equals(obj.getChannelId(), query.getChannelId())) {
//                parentChannelId = channelServiceCategoryBService.getAvailableCategoryChannelId(obj.getParentId());
//            }
//            if (NumberUtil.isPositiveInteger(parentChannelId)) {
//                channelProductMaps = Optional.ofNullable(channelProductMapService.listByQuery(ChannelProductMapQuery.builder().channelId(parentChannelId).build())).orElse(Collections.emptyList());
//            }
//        } catch (PlatException e) {
//            logger.error("渠道没配置可用的分类", e);
//        }
//
//        Map<Integer, List<ChannelProductMap>> mapResult = channelProductMaps.stream().collect(Collectors.groupingBy(ChannelProductMap::getProductId));
//        Map<Integer, String> parentIdMap = new HashMap<>();
//        Map<Integer, String> subIdMap = new HashMap<>();
//        mapResult.forEach((key, value) -> {
//            StringBuffer channelProductParentIdStr = new StringBuffer();
//            StringBuffer channelProductSubIdStr = new StringBuffer();
//            int count = 1;
//            for (ChannelProductMap e : value) {
//                channelProductParentIdStr.append("父ID").append(count).append(":").append(e.getChannelProductParentId()).append("；");
//                channelProductSubIdStr.append("子ID").append(count).append(":").append(e.getChannelProductSubId()).append("；");
//                count++;
//            }
//
//            if (channelProductParentIdStr.toString().length() > 0) {
//                channelProductParentIdStr.deleteCharAt(channelProductParentIdStr.length() - 1);
//            }
//
//            if (channelProductSubIdStr.toString().length() > 0) {
//                channelProductSubIdStr.deleteCharAt(channelProductSubIdStr.length() - 1);
//            }
//
//            parentIdMap.put(key, channelProductParentIdStr.toString());
//            subIdMap.put(key, channelProductSubIdStr.toString());
//        });
//
//        mav.addObject("parentIdMap", parentIdMap);
//        mav.addObject("subIdMap", subIdMap);
//
//        Map<Integer, String> showTypeMap = MasterDict.vtDtoToMap(ProductDict.getProductErpEsTypeList());
//        tableList.forEach(e -> e.setShowTypeName(showTypeMap.get(e.getShowType())));
//        mav.addObject("items", tableList);
//        mav.addObject("channelId", query.getChannelId());
//        mav.addObject("vo", query);
//
//        List<VtDTO> categOneList = Lists.newArrayList();
//        if (Objects.nonNull(query.getServCategId())) {
//            categOneList = Optional
//                    .ofNullable(servAssCategoryService.findCategoryOneByServIdAndShowType(query.getServCategId(), query.getShowType()))
//                    .orElse(Collections.emptyList()).stream().map(mm -> new VtDTO(mm.getCategId(), mm.getName())).collect(Collectors.toList());
//        }
//        mav.addObject("categOneList", categOneList);
//        List<VtDTO> categList = Lists.newArrayList();
//        if (NumberUtil.isPositiveInteger(query.getCategOneId())) {
//            BaseCategoryQuery categoryQuery = new BaseCategoryQuery();
//            categoryQuery.setParentId(query.getCategOneId());
//            categoryQuery.setStatus(GlobalConsts.YES);
//            categoryQuery.setShowType(query.getShowType());
//            categList = Optional.ofNullable(baseCategoryService.listPageByQuery(categoryQuery)).orElse(Collections.emptyList()).stream()
//                    .map(mm -> new VtDTO(mm.getCategId(), mm.getName())).collect(Collectors.toList());
//        }
//        mav.addObject("categList", categList);
//        return mav;
//    }
//
//    /**
//     * 结算信息
//     *
//     * @param channelId the channel id
//     * @return the model and view
//     * @author xiangjunming
//     * @since 2019/9/5
//     */
//    @RequestMapping(value = "settle")
//    @RequiresPermissions("/channel/settle/addEditView.action")
//    @ReadOnlyConnection
//    public ModelAndView settle(Integer channelId, String addFlag) {
//        ModelAndView mav = new ModelAndView("channel/settle");
//        Channel obj = channelService.findByKey(channelId);
//        ChannelSettle channelSettle = channelSettleService.findByKey(channelId);
//        if (channelSettle == null) {
//            channelSettle = new ChannelSettle();
//        }
//        Integer mergeSettle = getMergeSettle(channelId);
//        obj.setMergeSettle(mergeSettle);
//        channelSettle.setMergeSettle(mergeSettle);
//        ChannelSettleCostVO channelSettleCostVO = new ChannelSettleCostVO();
//        BeanUtils.copyProperties(channelSettle, channelSettleCostVO);
//        channelSettleCostVO.setCustomerCostYuan(narrow(channelSettleCostVO.getCustomerCost()));
//        channelSettleCostVO.setComprehensiveServiceFeeYuan(narrow(channelSettleCostVO.getComprehensiveServiceFee()));
//        channelSettleCostVO.setPromotionServiceFeeYuan(narrow(channelSettleCostVO.getPromotionServiceFee()));
//        mav.addObject("obj", obj);
//        mav.addObject("channelSettle", channelSettleCostVO);
//        mav.addObject("statementModes", ChannelStatementModeEnum.values());
//        mav.addObject("weeks", WeekEnum.listVtDTO());
//        mav.addObject("days", IntStream.range(1, 29).boxed().map(n -> new VtDTO(n, n + "日")).collect(Collectors.toList()));
//        mav.addObject("flag", 7);
//        mav.addObject("addFlag", addFlag);
//        return mav;
//    }
//
//    /**
//     * 押金管理
//     *
//     * @param channelId the channel id
//     * @return the model and view
//     * @author xiangjunming
//     * @since 2019/9/5
//     */
//    @RequestMapping(value = "deposit")
//    @RequiresPermissions("/channel/deposit/addEditView.action")
//    @ReadOnlyConnection
//    public ModelAndView deposit(Integer channelId, String addFlag) {
//        ModelAndView mav = new ModelAndView("channel/deposit");
//        Channel obj = channelService.findByKey(channelId);
//        ChannelDeposit deposit = depositService.findByKey(channelId);
//        List<ChannelDepositLog> depositLogs = depositLogService.lisyByChannelId(channelId);
//        Integer mergeSettle = getMergeSettle(channelId);
//        obj.setMergeSettle(mergeSettle);
//        mav.addObject("obj", obj);
//        mav.addObject("deposit", deposit);
//        mav.addObject("depositLogs", depositLogs);
//        mav.addObject("flag", 8);
//        mav.addObject("addFlag", addFlag);
//        return mav;
//    }
//
//    /**
//     * 导出excel
//     *
//     * @author xiangjunming
//     * @since 2019/9/5
//     */
//    // @RequestMapping(value = "exportExcel")
//    // @ReadOnlyConnection
//    // @RequiresPermissions("/channel/outputExcel.action")
//    // public void exportExcel(ChannelQuery query, HttpServletResponse response) throws Exception {
//    // query.setPageSize(100000);
//    // query.setPageIndex(1);
//    // List<Channel> items = channelService.listPageByQuery(query, getMcStaffId());
//    // if (items.isEmpty()) {
//    // return;
//    // }
//    // // 行业信息
//    // List<BaseCodeMap> baseCodeList = super.getBaseCodeList();
//    // Map<Integer, BaseCodeMap> baseCodeMap = baseCodeList.stream().collect(Collectors.toMap(p -> p.getMapId(), p -> p, (p, u) -> p));
//    //
//    // List<Integer> channelParentIds = items.stream()
//    // .map(Channel::getParentId)
//    // .filter(Objects::nonNull)
//    // .distinct()
//    // .collect(Collectors.toList());
//    // // 获取上级渠道
//    // Map<Integer, Channel> parentChannelMap = channelService.listByChannelIds(channelParentIds).stream()
//    // .collect(Collectors.toMap(p -> p.getChannelId(), p -> p, (p, u) -> p));
//    //
//    // // 获取押金
//    // List<Integer> channelIds = items.stream().map(Channel::getChannelId).collect(Collectors.toList());
//    // List<ChannelDeposit> channelDeposits = depositService.listByChannelIds(channelIds);
//    // Map<Integer, ChannelDeposit> channelDepositMap = channelDeposits.stream().collect(Collectors.toMap(p -> p.getChannelId(), p -> p, (p,
//    // u) -> p));
//    //
//    // // 获取结算信息
//    // List<ChannelSettle> channelSettles = channelSettleService.listAll();
//    // Map<Integer, ChannelSettle> channelSettleMap = channelSettles.stream().collect(Collectors.toMap(p -> p.getChannelId(), p -> p, (p, u)
//    // -> p));
//    //
//    // List<ChannelExportExcelVO> vos = new ArrayList<>(items.size());
//    // items.forEach(item -> {
//    // String parentName = (item.getParentId() == null || item.getParentId() == GlobalConsts.NO) ? item.getName() :
//    // getNull(parentChannelMap.get(item.getParentId()), p -> p.getName());
//    // ChannelDeposit deposit = channelDepositMap.get(item.getChannelId());
//    // ChannelSettle settle = channelSettleMap.get(item.getChannelId());
//    // BaseCodeMap baseCode = baseCodeMap.get(item.getIndustryId());
//    //
//    // ChannelExportExcelVO exportExcelVO = ChannelExportExcelVO.builder()
//    // .channelId(item.getChannelId())
//    // .status(StatusEnum.getName(item.getStatus()))
//    // .plat(GlobalConsts.getPlatName(item.getPlat()))
//    // .oneDeptName(item.getOneDeptName())
//    // .deptName(item.getDeptName())
//    // .salesmanName(item.getSalesmanName())
//    // .abutmenterName(item.getAbutmenterName())
//    // .channelTypeName(ChannelTypeEnum.getName(item.getChannelType()))
//    // .industryName(getNull(baseCode, p -> p.getName()))
//    // .levelName(ChannelLevelEnum.getName(item.getLevel()))
//    // .companyName(item.getCompanyName())
//    // .parentName(parentName)
//    // .name(item.getName())
//    // .innerName(item.getInnerName())
//    // .anotherName(item.getAnotherName())
//    // .accessModeName(getNull(item.getAccessMode(), p -> this.convertNameByStr(p, (s) -> ChannelAcessModeEnum.getName(s))))
//    // .hidden(YesNoEnum.getName(item.getHidden()))
//    // .contractStartDate(DateUtil.toString(item.getContractStartDate(), DateUtil.FORMAT_DATE3))
//    // .contractExpiresDate(DateUtil.toString(item.getContractExpiresDate(), DateUtil.FORMAT_DATE3))
//    // .contact(item.getContact())
//    // .applique(YesNoEnum.getName(item.getApplique()))
//    // .prepayType(YesNoEnum.getName(item.getPrepayType()))
//    // .inAdvanceLimit(ChannelAdvanceLimitEnum.getName(item.getInAdvanceLimit()))
//    // .inRestPaymentLimit(ChannelRestPaymentLimitEnum.getName(item.getInRestPaymentLimit()))
//    // .outAdvanceLimit(ChannelAdvanceLimitEnum.getName(item.getOutAdvanceLimit()))
//    // .outRestPaymentLimit(ChannelRestPaymentLimitEnum.getName(item.getOutRestPaymentLimit()))
//    // .showOrderPrice(YesNoEnum.getName(item.getShowOrderPrice()))
//    // .sendMsg(YesNoEnum.getName(item.getSendMsg()))
//    // .platformType(YesNoEnum.getName(item.getPlatformType()))
//    // .checkCompanyBank(YesNoEnum.getName(item.getCheckCompanyBank()))
//    // .deposit(getNull(deposit, p -> NumberUtil.convertMoneyToYuan(p.getBalance())))
//    // .settleCycle(getNull(settle, p -> ChannelSettleCycleEnum.getName(p.getSettleCycle())))
//    // .channelFinancerName(item.getChannelFinancerName())
//    // .financialRules(getNull(settle, p -> ChannelFinancialRulesEnum.getName(p.getFinancialRules())))
//    // .desc(item.getDesc()).build();
//    // vos.add(exportExcelVO);
//    // });
//    //
//    // ExportExcelBuilder excel = new ExportExcelBuilder();
//    // LinkedHashMap<String, String> fieldMap = Maps.newLinkedHashMap();
//    //
//    // fieldMap.put("channelId", "渠道ID");
//    // fieldMap.put("status", "渠道状态");
//    // fieldMap.put("plat", "所属平台");
//    // fieldMap.put("oneDeptName", "所属一级部门");
//    // fieldMap.put("deptName", "所属二级部门");
//    // fieldMap.put("salesmanName", "商务BD");
//    // fieldMap.put("abutmenterName", "运营责任人姓名");
//    // fieldMap.put("channelTypeName", "渠道类型");
//    // fieldMap.put("industryName", "所属行业");
//    // fieldMap.put("levelName", "渠道等级");
//    // fieldMap.put("companyName", "渠道公司名称");
//    // fieldMap.put("parentName", "上级渠道");
//    // fieldMap.put("name", "渠道名称");
//    // boolean showInnerName = StaffAdminService.isPermitted("/channel/showInnerName.action");
//    // if (showInnerName) {
//    // fieldMap.put("innerName", "渠道内部名称");
//    // }
//    // fieldMap.put("anotherName", "渠道别名");
//    // fieldMap.put("accessModeName", "接入方式");
//    // fieldMap.put("hidden", "后台录单");
//    // fieldMap.put("contractStartDate", "合同开始日期");
//    // fieldMap.put("contractExpiresDate", "合同到期日期");
//    // fieldMap.put("contact", "渠道方联系人");
//    // fieldMap.put("applique", "是否允许贴花");
//    // fieldMap.put("prepayType", "允许渠道预收");
//    // fieldMap.put("inAdvanceLimit", "保内预收限制");
//    // fieldMap.put("inRestPaymentLimit", "保内尾款限制");
//    // fieldMap.put("outAdvanceLimit", "保外预收限制");
//    // fieldMap.put("outRestPaymentLimit", "保外尾款限制");
//    // fieldMap.put("showOrderPrice", "透传订单价格");
//    // fieldMap.put("sendMsg", "允许发送短信");
//    // fieldMap.put("platformType", "允许修改渠道");
//    // fieldMap.put("checkCompanyBank", "是否打款给渠道方");
//    // fieldMap.put("deposit", "押金金额");
//    // fieldMap.put("settleCycle", "结算周期");
//    // fieldMap.put("channelFinancerName", "渠道方财务对接人姓名");
//    // fieldMap.put("financialRules", "工程师维修费结算规则");
//    // fieldMap.put("desc", "工程师提醒");
//    //
//    // ExportExcelBuilder.ExcelSheet<ChannelExportExcelVO> sheet1 = excel.createExcelSheet("sheet1", vos, fieldMap, true);
//    //
//    // sheet1.createFreezePane(0, 1, 0, 1).builderData();
//    // excel.exportExcel(response, "渠道信息");
//    // }
//
//    /**
//     * 推广码
//     *
//     * @param channelId the channel id
//     * @return the model and view
//     * @author tanbiao
//     * @since 2019/12/25
//     */
//    @RequestMapping(value = "promoCode")
//    @RequiresPermissions("/channel/promoCode.action")
//    @ReadOnlyConnection
//    public ModelAndView promoCode(Integer channelId) {
//        ModelAndView mav = new ModelAndView("channel/promocode");
//        Channel obj = channelService.findByKey(channelId);
//        Integer mergeSettle = getMergeSettle(channelId);
//        obj.setMergeSettle(mergeSettle);
//        mav.addObject("obj", obj);
//        mav.addObject("flag", 11);
//        return mav;
//    }
//
//    /**
//     * 获取图片二维码
//     *
//     * @param response
//     */
//    @RequestMapping(value = "qrCode", method = RequestMethod.GET)
//    @RequiresPermissions("/channel/promoCode.action")
//    public void getGifCaptcha(HttpServletResponse response, HttpServletRequest request, String url) {
//
//        // 告诉客户端输出的格式
//        response.setHeader("Pragma", "No-cache");
//        response.setHeader("Cache-Control", "no-cache");
//        response.setDateHeader("Expires", 0);
//        response.setContentType("image/jpg");
//
//        // 嵌入二维码的图片路径
//        ClassPathResource resource = new ClassPathResource("static/images/u964.jpg");
//        // String imgPath = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"static/images/u964.jpg";
//        // logger.info("=====imgPath:{}",resource.ge);
//        try {
//            BufferedImage image = QRCodeUtil.createImage(url, resource.getInputStream(), true);
//            ImageIO.write(image, "JPG", response.getOutputStream());
//            response.getOutputStream().flush();
//        } catch (Exception e) {
//            logger.error("=====生成二维码出错..", e);
//        }
//    }
//
//    @RequestMapping(value = "downloadQrCode")
//    @RequiresPermissions("/channel/promoCode.action")
//    public void downloadQrCode(HttpServletResponse response, String url) throws Exception {
//        response.setContentType("application/octet-stream");
//        response.setHeader("content-type", "application/octet-stream");
//        // 设置文件名
//        String fileName = (new SimpleDateFormat("yyyyMMddhhmm")).format(new Date());
//        response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "utf-8") + ".jpg");
//        BufferedInputStream bis = null;
//        ByteArrayOutputStream bos = new ByteArrayOutputStream();
//        // 嵌入二维码的图片路径
//        // String imgPath = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"static/images/u964.jpg";
//        ClassPathResource resource = new ClassPathResource("static/images/u964.jpg");
//        // logger.info("=====imgPath:{}",resource);
//        try {
//            BufferedImage image = QRCodeUtil.createImage(url, resource.getInputStream(), true);
//            ImageIO.write(image, "jpg", bos);
//            bis = new BufferedInputStream(new ByteArrayInputStream(bos.toByteArray()));
//            OutputStream os = response.getOutputStream();
//            IOUtils.copy(bis, os);
//        } catch (Exception e) {
//            logger.error("=====下载二维码出错..", e);
//            throw e;
//        } finally {
//            if (bis != null) {
//                try {
//                    bis.close();
//                } catch (IOException e) {
//
//                }
//            }
//            if (bos != null) {
//                try {
//                    bos.close();
//                } catch (IOException e) {
//
//                }
//            }
//        }
//    }
//
//    /**
//     * 部门联动
//     *
//     * @param parentId
//     */
//    @RequestMapping(value = "listChilds")
//    @ResponseBody
//    public ResponseDTO listChilds(@RequestParam(value = "parentId", defaultValue = "1") Integer parentId, @RequestParam(value = "selectVal", defaultValue = "0") Integer selectVal) {
//        // Integer deptId = body.getBody().getParentId();
//
//        ResponseDTO<List<DeptDRO>> responseDTO = deptListRemoteService.listDeptByParentId(parentId, null);
//
//        List<DeptDRO> items = responseDTO.getData();
//        List<TreeNodeDTO> vtItems = new ArrayList<>();
//        items.forEach(item -> {
//            vtItems.add(new TreeNodeDTO(item.getDeptName(), item.getDeptId(), Objects.equals(selectVal, item.getDeptId())));
//        });
//        // 初次加载如果存在选中的值，加载它对应的父节点
//        if (!NumberUtil.isNullOrZero(selectVal)) {
//            List<DeptDRO> parentNodes = new ArrayList<>();
//            // 根节点id
//            Integer levelOneParentId = getParentId(selectVal, parentNodes);
//            if (!Objects.equals(selectVal, levelOneParentId)) {
//                // 当前节点的顶级节点，
//                TreeNodeDTO one = vtItems.stream().filter(e -> Objects.equals(e.getValue(), levelOneParentId)).findFirst().get();
//                // 从后往前遍历
//                for (int j = parentNodes.size() - 1; j >= 0; j--) {
//                    DeptDRO oneDro = parentNodes.get(j);
//                    ResponseDTO<List<DeptDRO>> oneDroDTO = deptListRemoteService.listDeptByParentId(oneDro.getParentId(), null);
//                    List<DeptDRO> oneItems = oneDroDTO.getData();
//                    List<TreeNodeDTO> vtOneItems = new ArrayList<>();
//                    oneItems.forEach(item -> {
//                        vtOneItems.add(new TreeNodeDTO(item.getDeptName(), item.getDeptId(), Objects.equals(selectVal, item.getDeptId())));
//                    });
//
//                    if (CollectionUtils.isEmpty(one.getChildren())) {
//                        one.setChildren(vtOneItems);
//                    } else {
//                        one.getChildren().stream().filter(e -> Objects.equals(e.getValue(), oneDro.getParentId())).findFirst().get()
//                                .setChildren(vtOneItems);
//                    }
//                }
//            }
//        }
//
//        return ResponseDTO.success(vtItems, String.format("共%s个部门", vtItems.size()));
//    }
//
//    /**
//     * 描述: 复制渠道信息页面
//     *
//     * @author guoqiao
//     * @since 2021/6/7 16:53
//     */
//    @RequestMapping(value = "copyChannel")
//    @ReadOnlyConnection
//    public ModelAndView copyChannel() {
//
//        return new ModelAndView("channel/copyChannel");
//    }
//
//    private Integer getParentId(Integer deptId, List<DeptDRO> parentNodes) {
//        ResponseDTO<DeptDRO> resSelectDRO = deptListRemoteService.getDept(deptId);
//        if (resSelectDRO.isSuccess()) {
//            // 当前节点的父节点
//            DeptDRO selectDRO = resSelectDRO.getData();
//            Integer selectParentId = selectDRO.getParentId();
//            if (!Objects.equals(selectParentId, GlobalConsts.NO)) {
//                parentNodes.add(selectDRO);
//                return getParentId(selectParentId, parentNodes);
//            } else {
//                return selectDRO.getDeptId();
//            }
//        }
//        return null;
//    }
//
//    private String convertNameByStr(String str, Function<Integer, String> fun) {
//        if (StringUtil.isBlank(str)) {
//            return null;
//        }
//        String[] split = str.split(",");
//        StringBuilder builder = new StringBuilder();
//        for (String s : split) {
//            String name = fun.apply(Integer.valueOf(s));
//            builder.append(name).append(",");
//        }
//        builder.deleteCharAt(builder.length() - 1);
//        return builder.toString();
//    }
//
//    private static <T, R> R getNull(T t, Function<T, R> u) {
//        BiFunction<T, Function<T, R>, R> nullElse = (p, f) -> p == null ? null : f.apply(p);
//        return nullElse.apply(t, u);
//    }
//
//    private String narrow(Object dividend) {
//        if (Objects.isNull(dividend)) {
//            return "";
//        }
//        double div = MathUtil.div(Integer.parseInt(dividend.toString()), MasterDict.COEFFICIENT_MAGNIFICATION, 2);
//        BigDecimal b = new BigDecimal(div);
//        return b.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
//    }
//
//    /**
//     * 分页获取渠道操作日志
//     *
//     * @param logQuery 查询条件
//     * @return
//     */
//    private List<ChannelLog> listPageChannelLogByChannelId(ChannelLogQuery logQuery) {
//        logQuery.setPageSize(10);
//        logQuery.setTotalCount(channelLogService.countByQuery(logQuery));
//        List<ChannelLog> channelLogs = channelLogService.listPageByQuery(logQuery);
//        for (ChannelLog channelLog : channelLogs) {
//            channelLog.setData(channelLogData(channelLog.getData()));
//        }
//        return channelLogs;
//    }
//
//    /**
//     * 格式化渠道操作日志的操作内容
//     *
//     * @param data JSONlIST 字符串
//     * @return string
//     */
//    private String channelLogData(String data) {
//        if (Strings.isNullOrEmpty(data)) {
//            return "";
//        }
//        StringBuffer stringBuffer = new StringBuffer();
//        int index = 1;
//        String content = "<p>%s,%s：%s > %s<p/>";
//        String specialContent = "<p>%s,%s<p/>";
//        List<CompareObjectUtil.CompareField> list = JSON.parseArray(data, CompareObjectUtil.CompareField.class);
//        for (CompareObjectUtil.CompareField x : list) {
//            if (CompareObjectUtil.getNotLogFieldList().contains(x.getField())) {
//                stringBuffer.append(String.format(specialContent, index++, x.getFieldName()));
//                continue;
//            }
//            stringBuffer.append(String.format(content, index++, x.getFieldName(),
//                    StringUtils.isEmpty(x.getOldValue()) ? "无" : mosaicAlipayName(ChannelLogUtil.englishToChineseConversion(x.getField(), x.getOldValue()),x.getField()),
//                    StringUtils.isEmpty(x.getNewValue()) ? "无" : mosaicAlipayName(ChannelLogUtil.englishToChineseConversion(x.getField(), x.getNewValue()),x.getField())));
//        }
//        return stringBuffer.toString();
//    }
//
//    /**
//     *
//     * @param withdrawName
//     * @param field
//     * @return
//     */
//    private Object mosaicAlipayName(Object withdrawName,String field) {
//        //渠道方电话
//        if("mobile".equals(field)){
//            return DataUtils.maskMobile(String.valueOf(withdrawName));
//        }
//        //渠道方
//        if("financerPhone".equals(field)){
//            return DataUtils.maskMobile(String.valueOf(withdrawName));
//        }
//        //微信号
//        if("wechatAccount".equals(field)){
//            return DataUtils.wxAccount(String.valueOf(withdrawName));
//        }
//        //支付宝
//        if("alipayAccount".equals(field)){
//            return DataUtils.wxAccount(String.valueOf(withdrawName));
//        }
//        //银行卡
//        if("bankAccount".equals(field)){
//            if(DataUtils.isNumeric(withdrawName.toString())) {
//                //银行卡号
//                String regex = "(\\w{4})(.*)(\\w{4})";
//                Matcher m = Pattern.compile(regex).matcher(withdrawName.toString());
//                if (m.find()) {
//                    String rep = m.group(2);
//                    StringBuilder sb = new StringBuilder();
//                    for (int i = 0; i < rep.length(); i++) {
//                        sb.append("*");
//                    }
//                    return withdrawName.toString().replaceAll(rep, sb.toString());
//                }
//            }
//        }
//        return withdrawName;
//    }
//
//}